<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
        }
        div {
            position: relative;
            width: 100px;
            height: 100px;
            background-color: #00ff00;
        }
    </style>
    <script>
        window.onload = function () {
            var btn = document.getElementById("btn");
            var btn1 = document.getElementById("btn1");
            var box = document.getElementById("box");
            var box1 = document.getElementById("box1");
            btn.addEventListener("click", function () {
                animate(box, 500, 10);
                animate(box1, 500, 10);
            }, false)
            btn1.addEventListener("click", function () {
                animate(box, 1000, 10);
                animate(box1, 1000, 10);
            }, false)

            function animate(element, target ,step) {
                clearInterval(element.timerId);
                element.timerId = setInterval(function () {
                    var current = element.offsetLeft;//当前的距离
                    //var step = 10;
                    step = Math.abs(step);
                    step = current > target ? -step : step;
                    if (Math.abs(current - target) >= Math.abs(step)) {
                        //盒子的距离 = 当前的距离 + 步长
                        element.style.left = current + step + "px";
                    } else {
                        element.style.left = target + "px";//手动放到目标位置
                        clearInterval(element.timerId);//清理定时器
                    }
                }, 15)
            }
        }
    </script>
</head>
<body>
<input type="button" id="btn" value="移动到500"/>
<input type="button" id="btn1" value="移动到1000"/>

<div id="box"></div>
<div id="box1"></div>
</body>
</html>